<template>
	<view class="container">
			<!-- 地址edit -->
			<view class="form">
				<form @submit="formSubmit">
					<view class='addAddress'>
					   <view class='list'>
						  <view class='item acea-row row-between-wrapper'>
							  <view class='name'>姓名</view>
							  <input type='text' placeholder='请输入姓名' name='consignee' :value="userAddress.consignee" placeholder-class='placeholder'></input>
						  </view>
						  <view class='item acea-row row-between-wrapper'>
							  <view class='name'>联系电话</view>
							  <input type='text' placeholder='请输入联系电话' name="phone" :value='userAddress.phone' placeholder-class='placeholder'></input>
						  </view>
						  <view class='item acea-row row-between-wrapper'>
							  <view class='name'>所在地区</view>
							  <picker mode="multiSelector" @change="bindRegionChange" @columnchange="bindMultiPickerColumnChange" :value="valueRegion" :custom-item="customItem" :range="multiArray">
								<view class='acea-row row-between-wrapper'>
								  <view class="picker">{{region[0]}}，{{region[1]}}，{{region[2]}}</view>
								  <view class='iconfont icon-dizhi font-color'></view>
								</view>
							  </picker>
						  </view>
							<view class='item acea-row row-between-wrapper'>
							  <view class='name'>详细地址</view>
							  <input type='text' placeholder='请填写具体地址' name='address' placeholder-class='placeholder' :value='userAddress.address'></input>
						  </view>
					   </view>
					   <view class='default acea-row row-middle'>
						  <checkbox-group @change='changeIsDefault'><checkbox :checked="userAddress.isDefault == 1 ? true : false"/>设置为默认地址</checkbox-group>
					   </view>
					   <button class='keepBnt bg-color' formType="submit">立即保存</button>
					   <view class="wechatAddress" @click="getWxAddress">导入微信地址</view>
					</view>
				</form>
			</view>
	</view>
</template>

<script>
	import { editAddress, getAddressDetail } from '@/api/address.js'
	import { getCityAll } from '@/api/information.js'
	export default {
		props: ['addressId', 'from'],
		data() {
			return {
				info: {},
				regionDval: ['浙江省', '杭州市', '滨江区'],
			
				id: 0, //地址id
				userAddress: {}, //地址详情
				region: ['省', '市', '区'],
				valueRegion: [0, 0, 0],
				
				district: [],
				multiArray: [],
				multiIndex: [0, 0, 0],
				cityId: 0,
				defaultRegion: ['广东省', '广州市', '番禺区'],
				defaultRegionCode: '110101',
				defaultName: "请选择您所在的地区",
				fromPage: this.from
			}
		},
		mounted() {
			// this.$bus.$on('editAddr',(data)=>{
			// 	console.log('监听到了',data);
			// })
			this.getCityAll()
		},
		methods: {
			
			// 返回
			back() {
				this.$emit('close')
			},
			// 添加地址
			addAddr() {
				this.showForm = true
				this.title = "新增地址"
			},
			// 默认地址
			changeIsDefault(e){
				this.userAddress.isDefault = e.detail.value.length == 0 ? '0' : '1'
			},
			// 地址详情
			getAddressDetail(addressId) {
				getAddressDetail({addressId}).then(res => {
					if (res.code == 200) {
						this.userAddress = res.data
						this.region = [res.data.provinceName, res.data.cityName, res.data.areaName]
					} else {						
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none',
						});
						wx.navigateBack({ delta: 1 });
					}
				})
			},
			// 导入共享地址（小程序）
			getWxAddress: function() {
				let that = this;
				uni.authorize({
					scope: 'scope.address',
					success: function(res) {
						uni.chooseAddress({
							success: function(res) {
								that.userAddress = {
									consignee: res.userName,
									phone: res.telNumber,
									provinceName: res.provinceName,
									cityName: res.cityName,
									areaName: res.countyName,
									address: res.detailInfo,
									isDefault: that.userAddress.isDefault
								}
								that.region = [res.provinceName, res.cityName, res.countyName]
								console.log(res);
							},
							fail: function(res) {
								if (res.errMsg == 'chooseAddress:cancel') return that.$util
									.Tips({
										title: '取消选择'
									});
							},
						})
					},
					fail: function(res) {
						uni.showModal({
							title: '您已拒绝导入微信地址权限',
							content: '是否进入权限管理，调整授权？',
							success(res) {
								if (res.confirm) {
									uni.openSetting({
										success: function(res) {}
									});
								} else if (res.cancel) {
									return that.$util.Tips({
										title: '已取消！'
									});
								}
							}
						})
					},
				})
			},
			
			// 获取所有城市信息
			getCityAll() {
				getCityAll().then(res => {
					if(res.code == 200) {
						this.district = res.data
						// console.log(this.district);
						this.initialize()
					}
				})
			},
			
			initialize() {
				let that = this,
				province = [],
				city = [],
				area = [];
				let cityChildren = that.district[0].citylist || [];
				let areaChildren = cityChildren.length ? (cityChildren[0].arealist || []) : [];
				
				that.district.forEach((item, i) => {
					province.push(item.name);
					if (item.name === this.region[0]) {
						this.valueRegion[0] = i
						this.multiIndex[0] = i
					}
				});
				that.district[this.valueRegion[0]].citylist.forEach((item, i) => {
					if (this.region[1] == item.name) {
						this.valueRegion[1] = i
						this.multiIndex[1] = i
					}
					city.push(item.name);
				});
				that.district[this.valueRegion[0]]['citylist'][this.valueRegion[1]].arealist.forEach((item, i) => {
					if (this.region[2] == item.name) {
						this.valueRegion[2] = i
						this.multiIndex[2] = i
					}
					area.push(item.name);
				});
				this.multiArray = [province, city, area]
				// console.log(this.multiArray);
			},
			bindRegionChange: function(e) {
				let multiIndex = this.multiIndex,
				multiArray = this.multiArray,
				value = e.detail.value;
				this.region = [multiArray[0][value[0]], multiArray[1][value[1]], multiArray[2][value[2]]]
				this.valueRegion = [0, 0, 0]
				this.initialize();
			},
			bindMultiPickerColumnChange: function(e) {
				let that = this,
					column = e.detail.column,
					value = e.detail.value,
					currentCity = this.district[value] || {
						citylist: []
					},
					multiArray = that.multiArray,
					multiIndex = that.multiIndex;
					// console.log(column, value);
				multiIndex[column] = value;
				switch (column) {
					case 0:
						let areaList = currentCity['citylist'][0] || {
							arealist: []
						};
						multiArray[1] = currentCity.citylist.map((item) => {
							return item.name;
						});
						multiArray[2] = areaList.arealist.map((item) => {
							return item.name;
						});
						break;
					case 1:
						let cityList = that.district[multiIndex[0]]['citylist'][multiIndex[1]]['arealist'] || [];
						multiArray[2] = cityList.map((item) => {
							return item.name;
						});
						break;
					case 2:
						break;
				}
				// #ifdef MP || APP-PLUS
				this.$set(this.multiArray, 0, multiArray[0]);
				this.$set(this.multiArray, 1, multiArray[1]);
				this.$set(this.multiArray, 2, multiArray[2]);
				// #endif
							
				this.multiIndex = multiIndex
				// this.setData({ multiArray: multiArray, multiIndex: multiIndex});
			},
			/**
			   * 提交用户添加地址
			   * 
			  */
			  formSubmit(e){
			    var that = this, value = e.detail.value;
			    if (!value.consignee) {
					return uni.showToast({
							title: '请填写收货人姓名',
							duration: 1000,
							icon: 'none'
						});
				}
			    if (!value.phone) {
					return uni.showToast({
							title: '请填写联系电话',
							duration: 1000,
							icon: 'none'
						});
				}
			 //    if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(value.phone)) {
				// 	return uni.showToast({
				// 			title: '请输入正确的手机号码',
				// 			duration: 1000,
				// 			icon: 'none'
				// 		});
				// }
				if (this.region[0] =='省' || this.region[1] =='市' || this.region[2] =='区') {
					return uni.showToast({
							title: '请选择所在地区',
							duration: 1000,
							icon: 'none'
						});
				}
			    
			    if (!value.address) {
					return uni.showToast({
							title: '请填写详细地址',
							duration: 1000,
							icon: 'none'
						});
				}
			    value.id=this.addressId
			    value.provinceName = this.region[0]
			    value.cityName = this.region[1]
			    value.areaName = this.region[2]
			    value.isDefault = this.userAddress.isDefault == 1 ? 1 : 0;
				console.log(this.addressId, this.fromPage);
				const url = +this.addressId > 0 ? '/users/address/' + this.addressId : '/users/address/add'
			    editAddress(value, url).then(res=>{
					if (res.code == 200) {
						if (this.fromPage = 'order') {
							this.$emit('success')
						} else {
							this.$emit('success')
						}
					} else {
						uni.showToast({
							title: res.msg,
							duration: 1000,
							icon: 'none',
						});
					}
			    })
			  }
		},
		watch: {
			addressId(val) {
				this.getAddressDetail(val)
			}
		}
	}
</script>

<style lang="less" scoped>	
	.addAddress .list{background-color:#fff;}
	.addAddress .list .item{padding:0 30rpx;height:90rpx;border-top:1rpx solid #eee;}
	.addAddress .list .item .name{width:195rpx;font-size:30rpx;color:#333;}
	.addAddress .list .item input{width:475rpx;font-size:30rpx;}
	.addAddress .list .item .placeholder{color:#ccc;}
	.addAddress .list .item picker{width:475rpx;}
	.addAddress .list .item picker .picker{width:410rpx;font-size:30rpx;}
	.addAddress .list .item picker .iconfont{font-size:43rpx;}
	.addAddress .default{padding:0 30rpx;height:90rpx;background-color:#fff;margin-top:23rpx;}
	.addAddress .default checkbox{margin-right:15rpx;}
	.addAddress .keepBnt{width:690rpx;height:86rpx;border-radius:50rpx;text-align:center;line-height:86rpx;margin:50rpx auto;font-size:32rpx;color:#fff;}
	.addAddress .wechatAddress{width:690rpx;height:86rpx;border-radius:50rpx;text-align:center;line-height:86rpx;margin:0 auto;font-size:32rpx;color:#fe960f;border:1px solid #fe960f;}
	.bg-color{background-color:#e93323!important;}
</style>
